from django.db import transaction
from rest_framework import serializers
from tencentcloud.nlp.v20190408.models import Category

from apps.goods.models import SKUImage, SKU, SPU, SpecificationOption, SPUSpecification, Brand, GoodsChannel, \
    SKUSpecification, GoodsCategory, GoodsChannelGroup
from apps.orders.models import OrderInfo, OrderGoods


class ImageSerialzier(serializers.ModelSerializer):
    sku = serializers.PrimaryKeyRelatedField(read_only=True)
    class Meta:
        model = SKUImage
        fields = ('sku', 'id', 'image')


# class SkuSerialzier(serializers.ModelSerializer):
#     class Meta:
#         model = SKU
#         fields = '__all__'


class SkuSSerialzier(serializers.ModelSerializer):
    class Meta:
        model = SKU
        fields = ('id', 'name')

# 三级分类
class CategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = GoodsCategory
        fields = ('id', 'name')

# spu的数据获取
class SpuSerializer(serializers.ModelSerializer):
    class Meta:
        model = SPU
        fields = ('id', 'name')


# 一对多的表，，，，，序列化器嵌套    也就是关联序列化器
class SPUSpecsSerializer(serializers.ModelSerializer):
    class Meta:
        model = SpecificationOption
        fields = ['id', 'value']


class SPUSpecsSerializer2(serializers.ModelSerializer):
    spu = serializers.StringRelatedField()  # 关联的外键  SpecificationOption   关联了spu表
    spu_id = serializers.IntegerField()
    options = SPUSpecsSerializer(many=True)

    class Meta:
        model = SPUSpecification
        fields = '__all__'


# 关联序列化器
class SKUModerSerializer2(serializers.ModelSerializer):
    spec_id = serializers.IntegerField()
    option_id = serializers.IntegerField()
    class Meta:
        model = SKUSpecification
        fields = ('spec_id', 'option_id')


class SKUModerSerializer(serializers.ModelSerializer):
    category_id = serializers.IntegerField()
    spu_id = serializers.IntegerField()
    specs = SKUModerSerializer2(many=True)
    spu = serializers.StringRelatedField(read_only=True)#关联的外键
    category = serializers.StringRelatedField(read_only=True)
    class Meta:
        model = SKU
        exclude = ['create_time','update_time']
    # 重写create的方法,,实现增加的功能
    def create(self, validated_data):
        specs_data = validated_data.pop('specs')
        with transaction.atomic():
            start = transaction.savepoint()
            try:
                sku = SKU.objects.create(**validated_data)
                for specs_data in specs_data:
                    SKUSpecification.objects.create(sku=sku,**specs_data)
                transaction.savepoint_commit(start)
                return sku
            except:
                transaction.savepoint_rollback(start)
            return sku
    # 重写update的方法
    def update(self, instance, validated_data):
        specs_data = validated_data.pop('specs')
        # 修改首先要获取到单个数据，在进行修改数据
        # pk  = self.context.get('view').kwargs.get('pk')
        super().update(instance,validated_data)
        # SKU.objects.filter(id=pk).update(**validated_data)
        for specs_data in specs_data:
            # SKUSpecification.objects.filter(sku=instance,spec_id=specs_data.get('spu_id')).update(option_id=specs_data.get('option_id'))
            SKUSpecification.objects.filter(sku=instance,spec_id=specs_data.get('spu_id')).update(**specs_data)
        return instance





# 获取品牌数据
class BrandSerializer(serializers.ModelSerializer):
    class Meta:
        model = Brand
        fields= ('id','name')

# 获取一二三级分类
class CategoriesSerializer(serializers.ModelSerializer):
    class Meta:
        model = GoodsCategory
        fields = ('id','name')


# 实现spu的增删改查
class SPUSerializer(serializers.ModelSerializer):
    brand = serializers.StringRelatedField(read_only=True)
    brand_id =serializers.IntegerField()
    category1 = serializers.StringRelatedField(read_only=True)
    category1_id = serializers.IntegerField()
    category2 = serializers.StringRelatedField(read_only=True)
    category2_id = serializers.IntegerField()
    category3 = serializers.StringRelatedField(read_only=True)
    category3_id = serializers.IntegerField()

    class Meta:
        model = SPU
        exclude = ['create_time','update_time']
       # 商品详情:  商品包装   售后服务   只允许写入
        extra_kwargs = {
            'desc_detail':{'write_only':True},
            'desc_pack':{'write_only':True},
            'desc_service':{'write_only':True}
        }







#这是规格管理所需要的序列化器
class SpecsModelSerializer(serializers.ModelSerializer):
    spu = serializers.StringRelatedField(read_only=True)
    spu_id = serializers.IntegerField()
    class Meta:
        model  = SPUSpecification
        fields = ['id','name','spu','spu_id']
# 这是规格选项的管理
class SpecsModelSerializer2(serializers.ModelSerializer):
    spec= serializers.SlugRelatedField(read_only=True,slug_field='name')
    spec_id = serializers.IntegerField()
    class Meta:
        exclude = ['update_time','create_time']
        model = SpecificationOption

# 这是关于频道的序列化器
class GoodsChannelModelSerializer(serializers.ModelSerializer):
    category = serializers.StringRelatedField(read_only=True)
    group_id=  serializers.IntegerField()
    group = serializers.StringRelatedField(read_only=True)
    category_id= serializers.IntegerField()
    def get_grop(self,obj):
        return obj.group.name
    class Meta:
        model = GoodsChannel
        exclude = ['update_time','create_time']



# 这是关于频道的数据
class GoodsChannelGroupModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = GoodsChannelGroup
        fields = ['id','name']



class BrandModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = Brand
        fields = '__all__'



class SKUSSerializer(serializers.ModelSerializer):
    default_image_url = serializers.ImageField(source='default_image')
    class Meta:
        model = SKU
        fields = ['name','default_image_url']

class OrderGoodsSerializer(serializers.ModelSerializer):

    sku = SKUSSerializer()
    class Meta:
        model = OrderGoods
        fields = '__all__'


class OrderinfoSerializer(serializers.ModelSerializer):
    skus = OrderGoodsSerializer(many=True)
    class Meta:
        model = OrderInfo
        fields = '__all__'

class OrderinfoStatusSerializer(serializers.ModelSerializer):
    class Meta:
        model = OrderInfo
        fields = ['status']






